/*
 * Copyright (c) 2008 by 1eEurope (Switzerland) AG, Thalwil
 *
 * Customer:	1eEurope (Switzerland) AG
 * Project:		BKS
 * Created:		30.09.2008, WBL
 *
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Publishing.WebControls;

namespace By1eEurope.BKS.Controls
{
    /// <summary>
    /// Renders the Content of a RichtHtmlField with XHTML compliance
    /// </summary>
    public class BKSRichHtmlFieldControl : RichHtmlField
    {
        private Regex _regexIMG = new Regex("<img[^>]*style=\\\"?([^\\\"]*)\\\"?[^>]*alt=\\\"?([^\\x20]*)" +
                                              "\\\"?[^>]*src=\\\"?([^\\\"]*)\\\"?[^>]*border=\\\"?([^>]*)\\\"?" +
                                              "[^>]*>",
                                              RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
        private string _regexReplaceIMG = "<img style=\"$1\" src=\"$3\" alt=\"$2\" border=\"$4\" />";

        [Browsable(true)]
        private bool enableXHTMLCompliance;
        /// <value>
        /// Get or Set if XHTMLCompliance is enabled. Default is false.
        /// </value>
        public bool EnableXHTMLCompliance {
            get { return this.enableXHTMLCompliance; }
            set { this.enableXHTMLCompliance = value;  }
        }

        /// <summary>
        /// Adds XHTMLCompliance to the base method's output if enabled.
        /// </summary>
        /// <param name="output"></param>
        protected override void RenderFieldForDisplay(HtmlTextWriter output)
        {
            TextWriter tempWriter = new StringWriter();
            base.RenderFieldForDisplay(new HtmlTextWriter(tempWriter));

            string newHtml = tempWriter.ToString();
            if (EnableXHTMLCompliance == true)
            {
                newHtml = _regexIMG.Replace(newHtml, _regexReplaceIMG);
            }
            output.Write(newHtml);
        }
    }
}